using System;

namespace sforceExplorer
{
	public delegate void RequestEvent(SoapRecord soapRecord);
	public delegate void ResponseEvent(SoapRecord soapRecord);

	/// <summary>
	/// Summary description for LogTraceListener.
	/// </summary>
	public class LogTraceListener : System.Diagnostics.TraceListener
	{
		private SoapRecord soapRecord;


		public event RequestEvent RequestMade;
		public event ResponseEvent ResponseMade;

		public LogTraceListener()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		public override void WriteLine(string message)
		{
			Write(message);
		}

		public void OnResponseEvent() 
		{
			if (ResponseMade != null)
				ResponseMade(soapRecord);
		}
		public void OnRequestEvent() 
		{
			if (RequestMade != null)
				RequestMade(soapRecord);
		}
		public override void Write(string message)
		{
			string reqStart = "BEGINSOAPREQUEST";
			string respStart = "BEGINSOAPRESPONSE";

			if (message.StartsWith(reqStart))	
			{
				string msg = message.Substring(reqStart.Length);
				soapRecord = new SoapRecord();
				soapRecord.Request = msg;
				OnRequestEvent();
			}

			if (message.StartsWith(respStart))	
			{
				string msg = message.Substring(respStart.Length);
				if (soapRecord == null)
					soapRecord = new SoapRecord();

				soapRecord.Response = msg;
				OnResponseEvent();
			}
		}

	}
}
